#!/bin/bash

# This script creates a measurement archive that describes the following interface statistics
# with regards to time:
# - Count of all interfaces 
# - Interfaces that have their protocol up (Operational status of up)
# - Per interface percentage utilizatoin
#
# An entry(one line) from the archive takes the following form:
#    
#        Timestamp: UpInterfaceCount/TotalInterfaceCount, Interface1=PercentageUtilization, ...  
#
# The current utilization of a port is expressed in percentiles by the following formula:
#
#
#          Max(Delta(InOctets), Delta(OutOctets) * 8(20% management) * 100%
#          -------------------------------------------------------------
#                       ProbesInterval * InterfaceCapacity
#
# 
# The script takes as configurable parameters:
#
# - IP(s) of device(s)
# - SNMP community of devices(should be shred)
# - Interval inbetween the two probes needed by the calculation. Should be large enough (30s)
#   to accommodate for the lack of tracking time inbetween the different SNMP queries


#Data containers of local devices whose port utilization stats need to be obtained
device=( "192.168.1.1" "192.168.1.2" )
#SNMP community
community="public"
#Time between the two probes used in measuring interface utilization.
probeTime=30
#Statistics storage location
outputDir="/opt/perfSONARNC/SNMP\ archives/"


#
for ipAddrs in "${device[@]}"
do
	:
	#Get the operational status of interfaces
	ifOper=`snmpwalk -v 2c -c $community ${device[$i]} ifOperStatus`
	#Get the capacity of interfaces
	ifSpeed=`snmpwalk -v 2c -c $community ${device[$i]} ifSpeed`
	#Count how many interfaces this device has
	interfaceCount=`echo "$ifOper" | wc -l`

	#Do two consequtive probes of IF-MIB::ifInOctets and IF-MIB::ifOutOctets 30s apart so that utilization can be calculated
	ifInOctets[0]=`snmpwalk -v 2c -c  $community $ipAddrs ifInOctets`
	ifOutOctets[0]=`snmpwalk -v 2c -c  $community $ipAddrs ifOutOctets`
	sleep 30s
	ifInOctets[1]=`snmpwalk -v 2c -c  $community $ipAddrs ifInOctets`
	ifOutOctets[1]=`snmpwalk -v 2c -c  $community $ipAddrs ifOutOctets`
        

    #Build up an array of up interfaces by reading the contents of ifOperStatus
    index=0
    while IFS= read -r interfaceStatus
    do
        if [[ "$interfaceStatus" =~ "up" ]]; then
                #Extract interface index
                ifOperStatus[$index]=`echo "$interfaceStatus" | grep -oiE '\..*\s=' | sed 's/[^0-9]//g'`
                index=$((index + 1))
        fi
    done <<< "$ifOper"
    
    #Build up an array representing utilization of a port in the form intefaceIndex:PercentageUtilization
    for ifIndex in "${ifOperStatus[@]}"
    do
        :
        #Calculate input octets in interval
        probe1_inOctets=`echo -n "${ifInOctets[0]}" | grep -i "ifInOctets."$ifIndex | cut -d ' ' -f 4`
        probe2_inOctets=`echo -n "${ifInOctets[1]}" | grep -i "ifInOctets."$ifIndex | cut -d ' ' -f 4`
        measuredInputOctets="$(($probe2_inOctets - $probe1_inOctets))"

        #Calculate output octets in interval
        probe1_outOctets=`echo -n "${ifOutOctets[0]}" | grep -i "ifOutOctets."$ifIndex | cut -d ' ' -f 4`
        probe2_outOctets=`echo -n "${ifOutOctets[1]}" | grep -i "ifOutOctets."$ifIndex | cut -d ' ' -f 4`
        measuredOutputOctets="$(($probe2_outOctets - $probe1_outOctets))"
        
        #Get the max of in/out octets in interval or just save one of them if equal load
        if [[ $measuredInputOctets > $measuredOutputOctets || $measuredInputOctets -eq $measuredOutputOctets ]]; then
                maxOctets="$measuredInputOctets"
        else [[ measuredInputOctets < outUtilization ]]
                maxOctets="$measuredOutputOctets"
        fi

        #Get the capacity of this interface
        ifCapacity=`echo $ifSpeed | cut -d ' ' -f 4`

        #Calculate percentage utilization and store it
        num="$(($maxOctets*8*100))"
        denum="$(($probeTime*$ifCapacity))"
        ifPercentUtilization[$ifIndex]=`printf "%.2f\n" $(echo "scale=2; $num/$denum" | bc)`
    done
        #Write statistics to file
        echo -n `date +%s": "${#ifOperStatus[@]}"/"$interfaceCount",  "` >> $outputDir"/"$ipAddrs
        for i in  ${!ifPercentUtilization[*]}
        do
                :
                echo -n $i"="${ifPercentUtilization[$i]}", " >> $outputDir"/"$ipAddrs
        done
                echo >> $outputDir"/"$ipAddrs
done
